<template>
  <div ref="containerRef">
    <div class="text-[26px] font-bold">
      <button class="pr-3" :class="[ activeTab === 'question'? 'opacity-100' : 'opacity-30' ]" @click="activeTab = 'question'">My questions</button>
      <a-divider direction="vertical" :size="3" />
      <button class="pl-3" :class="[ activeTab === 'answer'? 'opacity-100' : 'opacity-30' ]" @click="activeTab = 'answer'">My answers</button>
    </div>
    <img src="@/assets/images/line-light.png"></img>
    <a-list
      class="list-demo-action-layout"
      :bordered="false"
      :split="false"
      :max-height="dynamicHeight"
      :data="flattenedQAData"
      @reach-bottom="fetchQAData(true)" 
      :scrollbar="scrollbar"
    >
      <template #item="{ item }">
        <a-list-item class="list-demo-item" action-layout="vertical" :class="{ 'ml-8 border-l-2 border-gray-300': item.isChild }">
          <template #actions>
            <span class="flex items-center h-[24px]">
            </span>
            <div class="absolute right-4">
              <span class="text-[16px] text-primary font-bold pr-2">{{ getMonthName(item.createAt) }}</span>
              <span class="text-[16px] font-bold pr-2">{{ getDayAndYear(item.createAt) }}</span>
              <span class="text-[16px] text-primary font-bold">{{ formatTime(item.createAt) }}</span>
            </div>
          </template>
          <a-list-item-meta>
            <template #title>
              <div class="text-[18px] font-bold" :class="{ 'text-gray-600': item.isChild }">
                {{ item.isChild ? '追问: ' : '' }}{{ item.question }}
              </div>
            </template>
          </a-list-item-meta>
        </a-list-item>
        <div class="px-4" :class="{ 'ml-8': item.isChild }">
          <!-- 气泡容器 -->
          <div class="bg-bgColorGrey rounded-xl shadow-sm relative mt-2"> <!-- 移除 overflow-hidden -->
            <!-- 左上角三角形 - 确保可见 -->
            <div class="absolute -top-[16px] left-0 w-0 h-0 border-l-[0px] border-r-[30px] border-b-[16px] border-l-transparent border-r-transparent border-b-bgColorGrey rounded-tl-[4px] z-10"></div>
            
            <!-- 气泡内容 -->
            <div class="p-6 bg-bgColorGrey rounded-tr-[14px]"> <!-- 确保内容区域有背景 -->
              <p class="text-gray-800 text-base leading-relaxed">
                {{ item.reply }}
              </p>
            </div>
            
            <!-- 底部按钮区域 -->
            <div class="bg-primary text-white py-1 px-4 text-center rounded-b-[14px] mb-6">
              <span class="text-[14px] font-medium">{{ item.isChild ? 'child reply' : 'what you replied to' }}</span>
            </div>
          </div>
        </div>
      </template>
    </a-list>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, nextTick } from 'vue'
import { getMonthName, getDayAndYear, formatTime } from '@/utils/tool'
import { qaDetailApi, qaListApi } from '@/api/qa';

// Props 定义
interface Props {
  uid?: string
}

const props = withDefaults(defineProps<Props>(), {
  uid: () => localStorage.getItem('uid') || ''
})

const activeTab = ref('question')

// 数据定义
const qaData = ref([] as any[])
const scrollbar = ref(true)

const query: any = ref({
  uid: props.uid,
  limit: 10,
  page: 1
})

// 获取问答列表
const isInitialized = ref(false)

const fetchQAData = (isLoadMore = false) => {
  // 如果还没初始化完成，不允许加载更多
  if (isLoadMore && !isInitialized.value) {
    return
  }
  
  if(isLoadMore) {
    query.value.page++
  } else {
    query.value.page = 1
    qaData.value = []
  }
  
  qaListApi(query.value).then(async (res: any) => {
    if (res.code === 0) {
      const promises = res.data.list.map(async (item: any) => {
        let detail: any = await getQaDetail(item.qid)
        const childPromises = item.childQid?.map(async (childQid: string) => {
          return getQaDetail(childQid)
        })
        await Promise.all(childPromises).then((results) => {
          detail.children = results
        })
        return { ...detail }
      })
      
      await Promise.all(promises).then((results) => {
        qaData.value = qaData.value.concat(results)
        // 标记初始化完成
        if (!isLoadMore) {
          isInitialized.value = true
        }
      })
    }
  })
}

// 组件挂载时获取数据
onMounted(() => {
  window.addEventListener('resize', handleResize)
  fetchQAData() // 初始化数据
  nextTick(() => {
    // 确保DOM渲染完成后再计算高度
  })
})

const getQaDetail = (qid: string) => {
  return new Promise((resolve) => {
		qaDetailApi(qid, 'display').then((res: any) => {
			if(res.code === 0) {
				resolve(res.data)
			} else {
				resolve({})
			}
		}).catch(() => {
			resolve({})
		})
	})
}

// 暴露方法给父组件
defineExpose({
  fetchQAData
})

// 窗口高度和组件元素引用
// 获取整个文档的滚动高度
const windowHeight = ref(document.documentElement.scrollHeight)
const containerRef = ref<HTMLElement>()

// 动态计算列表的最大高度
const dynamicHeight = computed(() => {
  if (!containerRef.value) return 240 // 默认值
  
  const rect = containerRef.value.getBoundingClientRect()
  const availableHeight = windowHeight.value - rect.top
  
  return Math.max(300, availableHeight) // 提高最小高度到300px
})

// 监听窗口大小变化
const handleResize = () => {
  windowHeight.value = window.innerHeight
}

// 组件挂载时获取数据
onMounted(() => {
  window.addEventListener('resize', handleResize)
  nextTick(() => {
    // 确保DOM渲染完成后再计算高度
  })
})

// 组件卸载时清理事件监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

// 计算属性：将嵌套的父子结构扁平化
const flattenedQAData = computed(() => {
  const flattened: any[] = []
  
  qaData.value.forEach((parent: any) => {
    // 添加父节点
    flattened.push({ ...parent, isChild: false })
    
    // 添加子节点
    if (parent.children && parent.children.length > 0) {
      parent.children.forEach((child: any) => {
        flattened.push({ ...child, isChild: true })
      })
    }
  })
  
  return flattened
})
</script>

<style scoped>
</style>